const mongoose = require('mongoose'); // mongo库
const bcrypt = require('bcryptjs') // 密码加密
const salt = bcrypt.genSaltSync(10) // 生成哈希长度

const AlipaySdk = require('alipay-sdk').default // ali支付SDK


module.exports = {
  objId: _id => mongoose.Types.ObjectId(_id), // 转化数据库_id
  // 编码密码
  encodePwd (pwd) {
    let hash = bcrypt.hashSync(pwd, salt) // 加密密码
    return hash
  },
  // 密码校验
  comparPwd (pwd, hash) {
    return bcrypt.compareSync(pwd, hash) // 密码校验 返回true/false
  },
  _alipaySdk: null, 
  async alipaySdk (type) {
    // 已存在直接返回
    if (this._alipaySdk && !type) return this._alipaySdk
    // 获取数据库配置信息
    let db = think.mongoose('mongo/alipay')
    let config = await db.findOne({})
    if (config) {
      this._alipaySdk = new AlipaySdk({ // 实例化ali支付SDK
        appId: config.appid,
        privateKey: config.privateKey,
        alipayPublicKey: config.alipayPublicKey,
        gateway: config.gateway,
        charset: 'utf-8',
        signType: 'RSA2'
      })
    }
    return this._alipaySdk
  },
  vipNum (vip) {
    let data = {}
    switch (vip) {
      case 0:
        data = { num: 3, money: 50, price: 0, name: '普通会员' } // 普通会员
        break;
      case 1:
        data = { num: 5, money: 100, price: 58, name: '白银会员' } // 白银会员
        break;
      case 2:
        data = { num: 8, money: 200, price: 188, name: '黄金会员' } // 黄金会员
        break;
      case 3:
        data = { num: 12, money: 300, price: 328, name: '砖石会员' } // 砖石会员
        break; 
      default:
        data = { num: Infinity, money: Infinity, price: 688, name: '至尊会员' } // 至尊会员
    }
    return data
  },
  dayTime () {
    let date = new Date()
    let start = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} 0:0:0`;
    let end = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} 11:59:59`;
    start = start.replace(/-/g,'/')
    end = end.replace(/-/g,'/')
    var timestamp = new Date(date).getTime();
    return {
      start: new Date(start).getTime(),
      end: new Date(end).getTime()
    }
  }
}